package com.geekgo.distributedlock.redissonlock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author geekgo
 * @version 2017/2/9 17:14
 */
public class SingleDistributedLockTemplate implements DistributedLockTemplate {

    private static final long DEFAULT_TIMEOUT = 5;
    private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;

    private RedissonClient redissonClient;

    public SingleDistributedLockTemplate(){}

    public SingleDistributedLockTemplate(RedissonClient redissonClient){
        this.redissonClient = redissonClient;
    }

    @Override
    public <T> T lock(DistributedLockCallback<T> callback) {
        return lock(callback,DEFAULT_TIMEOUT,DEFAULT_TIME_UNIT);
    }

    @Override
    public <T> T lock(DistributedLockCallback<T> callback, long leaseTime, TimeUnit timeUnit) {
        RLock lock = null;
        try {
            lock = redissonClient.getLock(callback.getLockName());
            lock.lock(leaseTime,timeUnit);
            return callback.process();
        } finally {
            if(lock != null){
                lock.unlock();
            }
        }

    }
    public void setRedissonClient(RedissonClient redissonClient){
        this.redissonClient = redissonClient;
    }
}
